package com.dawn.sinaoption.serviceimpl;

import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dawn.sinaoption.service.SinaService;
import com.dawn.trademanage.bean.TradeDetailBean;
import com.dawn.trademanage.bean.TradeInfoBean;
import com.dawn.trademanage.service.TradeManageService;
import com.dawn.usermanage.bean.UserBean;
import com.dawn.usermanage.service.UserManageService;
import com.dawn.utils.exceptions.DaoAccessException;

@Service
public class SinaServiceImpl implements SinaService {

	private static Logger logger = Logger.getLogger(SinaServiceImpl.class);

	@Autowired
	private TradeManageService tradeManageService;

	@Autowired
	private UserManageService userManageService;;

	public boolean sinaFollow(long userId, TradeInfoBean tradeInfo) {
		try {
			int tradePrice = tradeInfo.getUnitPrice();
			UserBean user = userManageService.findUserByUID(userId);
			user.setRemainNumByDay(user.getRemainNumByDay()-1);
			userManageService.updateUser(user);
			boolean increaseResult = tradeManageService.increaseBalance(user.getTtTradeinfo().getTradeId(), tradePrice);
			boolean reduceResult = tradeManageService.reduceBalance(tradeInfo.getTradeId(), tradePrice);
			if (!(increaseResult && reduceResult))
				throw new DaoAccessException();
			TradeDetailBean tradeDetailBean = new TradeDetailBean();
			tradeDetailBean.setFansId(userId);
			tradeDetailBean.setFollowedTime(Calendar.getInstance());
			tradeDetailBean.setTtTradeinfo(tradeInfo);
			tradeManageService.addTradeDetail(tradeDetailBean);
			return true;
		} catch (Exception e) {
			logger.error("Data access error.");
			throw new DaoAccessException();
		}
	}
}
